// 检查token是否有效
export const checkToken = () => {
  try {
    const token = uni.getStorageSync('token')
    return !!token // 返回 true 如果 token 存在，false 如果不存在
  } catch (error) {
    console.error('获取token失败：', error)
    return false
  }
}

// 跳转到对应的个人页面
export const navigateToMyPage = () => {
  if (checkToken()) {
    uni.navigateTo({
      url: '/pages/wode-dongtai/wode-dongtai'
    })
  } else {
    uni.navigateTo({
      url: '/pages/wode-kong/wode-kong'
    })
  }
}

// 初始化检查token并跳转
export const initAuthCheck = () => {
  if (checkToken()) {
    uni.reLaunch({
      url: '/pages/wode-dongtai/wode-dongtai'
    })
  } else {
    uni.reLaunch({
      url: '/pages/wode-kong/wode-kong'
    })
  }
}

// 验证 token 是否有效
export const verifyToken = async () => {
  try {
    const token = uni.getStorageSync('token')
    if (!token) return false

    const res = await uni.request({
      url: `${process.env.NODE_ENV === 'development'
        ? 'http://127.0.0.1:5000/api'
        : 'http://127.0.0.1:5000/api'}/user/info/detail`,
      method: 'POST',
      header: {
        'Authorization': token
      }
    })

    return res.data.code === 200
  } catch (error) {
    console.error('验证token失败：', error)
    return false
  }
}

// 检查是否需要登录的页面
const authPages = [
  'pages/wode-dongtai/wode-dongtai',
  'pages/wode-ziliao/wode-ziliao',
  'pages/setting/setting'
]

// 检查页面是否需要登录
export const checkNeedAuth = (url) => {
  return authPages.some(page => url.includes(page))
}

// 路由守卫
export const routeGuard = (url) => {
  if (checkNeedAuth(url) && !checkToken()) {
    uni.navigateTo({
      url: '/pages/wode-kong/wode-kong'
    })
    return false
  }
  return true
} 